from plantmanagement import db
from plantmanagement.models import Users
from plantmanagement.fun import Tools


class UserController:

    # 用户注册
    def insert(**kwargs):
        u = Users(head=kwargs['head'], nickname=kwargs['nickname'], openid=kwargs['openid'])
        user = Users.query.filter_by(nickname=kwargs['nickname']).count()


        if user > 0:
            users = Users.query.filter_by(openid=kwargs['openid']).first()
            z_token = Users.create_token(users.id)
            s = Users.query.filter_by(id=u.id).first()
            s.token=z_token

            return {
                'code': 200,
                'data': s.to_json(),
            }
        else:
            Tools.db_commit(u)
            users = Users.query.filter_by(openid=kwargs['openid']).first()
            z_token = Users.create_token(users.id)
            s = Users.query.filter_by(id=u.id).first()
            s.token = z_token

            return {
                'code': 200,
                'data': s.to_json(),
            }

    # 获取个人信息
    def queryUser(userid):
        s = Users.query.filter_by(id=userid).first()
        return {
            'code': 200,
            'data': s.to_json()
        }

    # 编辑个人信息
    def editUserInfo(**self):
        userid = self['userid']
        u = Users.query.filter_by(id=userid).first()
        u.head = self['head'] if self['head'] else u.head
        u.nickname = self['nickname'] if self['nickname'] else u.nickname
        Tools.db_commit(u)
        s = Users.query.filter_by(id=userid).first()
        return {
            'code': 200,
            'data': s.to_json()
        }
